package server.demo.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import server.demo.entity.Order;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Repository
public interface OrderRepository extends JpaRepository<Order, Long> {
    Optional<Order> findByOrderNumber(String orderNumber);
    
    List<Order> findByUserIdOrderByCreatedAtDesc(Long userId);
    
    @Query("SELECT o FROM Order o WHERE o.orderStatus = :status")
    List<Order> findByOrderStatus(@Param("status") Order.OrderStatus status);
    
    boolean existsByOrderNumber(String orderNumber);
    
    // 统计方法
    long countByOrderStatus(Order.OrderStatus orderStatus);
    
    long countByCreatedAtBetween(LocalDateTime start, LocalDateTime end);
    
    @Query("SELECT SUM(o.totalAmount) FROM Order o WHERE o.orderStatus = :status")
    BigDecimal sumTotalAmountByOrderStatus(@Param("status") Order.OrderStatus status);
    
    long countByUserId(Long userId);
    
    long countByUserIdAndOrderStatus(Long userId, Order.OrderStatus orderStatus);
    
    @Query("SELECT SUM(o.totalAmount) FROM Order o WHERE o.user.id = :userId AND o.orderStatus = :status")
    BigDecimal sumTotalAmountByUserIdAndOrderStatus(@Param("userId") Long userId, @Param("status") Order.OrderStatus status);
    
    @Query("SELECT t.trainNumber, COUNT(o) FROM Order o JOIN Ticket ticket ON o.id = ticket.order.id JOIN Train t ON ticket.train.id = t.id GROUP BY t.trainNumber ORDER BY COUNT(o) DESC")
    List<Object[]> findPopularTrainsByOrderCount(int limit);
}